package com.tju.eduStatistics.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tju.RandomUtil;
import com.tju.Result;
import com.tju.eduStatistics.client.UcenterClient;
import com.tju.eduStatistics.entity.Daily;
import com.tju.eduStatistics.mapper.DailyMapper;
import com.tju.eduStatistics.service.DailyService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.RandomUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 网站统计日数据 服务实现类
 * </p>
 *
 * @author gsc
 * @since 2022-01-19
 */
@Service
public class DailyServiceImpl extends ServiceImpl<DailyMapper, Daily> implements DailyService {

    @Autowired
    private UcenterClient ucenterClient;
    @Override
    public void registerCount(String day) {
        //统计某一天的注册人数，先删除之前的数据
        QueryWrapper<Daily> wrapper = new QueryWrapper<>();
        wrapper.eq("date_calculated",day);
        baseMapper.delete(wrapper);

        Result result = ucenterClient.countRegister(day);
        Map<String, Object> map = result.getData();
        //获取注册人数
        Integer count = (Integer) map.get("countRegister");
        //添加到数据库中

        Daily daily = new Daily();
        daily.setRegisterNum(count);//注册人数
        daily.setCourseNum(RandomUtils.nextInt(100,200));
        daily.setLoginNum(RandomUtils.nextInt(200,300));//登录数
        daily.setVideoViewNum(RandomUtils.nextInt(200,300));//视频流量数
        daily.setDateCalculated(day);//统计日期
        baseMapper.insert(daily);

    }

    @Override
    public Map<String, Object> showData(String type, String begin, String end) {
        QueryWrapper<Daily> wrapper = new QueryWrapper<>();
        wrapper.between("date_calculated",begin,end);
        wrapper.select("date_calculated",type);
        List<Daily> staList = baseMapper.selectList(wrapper);
        List<String> dateList = new ArrayList<>();
        List<Integer> numDataList = new ArrayList<>();
        for (Daily daily : staList) {
            dateList.add(daily.getDateCalculated());
            //通过type来判断应该返回什么数量
            if ("register_num".equals(type)){
                numDataList.add(daily.getRegisterNum());
            }
            if ("login_num".equals(type)){
                numDataList.add(daily.getLoginNum());
            }
            if ("video_view_num".equals(type)){
                numDataList.add(daily.getVideoViewNum());
            }
            if ("course_num".equals(type)){
                numDataList.add(daily.getCourseNum());
            }
        }
        Map<String, Object> map = new HashMap<>();
        map.put("dateList",dateList);
        map.put("numDataList",numDataList);
        return map;
    }
}
